﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.Controls
{
    public partial class CsvParser : PhoneApplicationPage
    {
        private string selectedFile;
        private DetailMatkul detMatkul;
        private ObservableCollection<DataImport> selectedItem = new ObservableCollection<DataImport>();

        public CsvParser()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.DETMATKUL))
            {
                detMatkul = (DetailMatkul)PhoneApplicationService.Current.State[Config.DETMATKUL];
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
            {
                Utility.GotoPage(this, "/Controls/StorageBrowser.xaml");
                StorageBrowser.CallerPage(this);
            }
        }

        public void SelectedFile(string selectedFile)
        {
            this.selectedFile = selectedFile;
        }

        private void ImportMember()
        {
            string url = string.Format("{0}&{1}", Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.IMPORT_MEMBER_KULIAH_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(GetObjectFromRecords());

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(importMember_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void importMember_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            try
            {
                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            ParseCSVFile();
        }

        private void buttonAccept_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Import all data?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                ImportMember();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/PerkuliahanDetailPage.xaml");
            NavigationService.RemoveBackEntry();
        }

        public void ParseCSVFile()
        {
            try
            {
                ObservableCollection<DataImport> list = GetObjectFromRecords();
                CsvListBox.ItemsSource = list;                
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private ObservableCollection<DataImport> GetObjectFromRecords()
        {
            int index = 0;
            string col1 = "Id Mhs", col2 = "Nip", col3 = "Matkul", col4 = "Semester", col5 = "Tahun";
            ObservableCollection<DataImport> list = new ObservableCollection<DataImport>();

            foreach (String[] record in GetRecords())
            {
                if (index < 1)
                {
                    col1 = record[0];
                    col2 = record[1];
                    col3 = record[2];
                    col4 = record[3];
                    col5 = record[4];
                }

                if (record.Length == 5 && index > 0)
                {
                    DataImport dtl = new DataImport()
                    {
                        Nim = record[0],
                        Nip = record[1],
                        Matkul = detMatkul.Id,
                        Semester = record[3],
                        TahunAjaran = record[4],

                        Col1 = col1,
                        Col2 = col2,
                        Col3 = col3,
                        Col4 = col4,
                        Col5 = col5,
                    };
                    list.Add(dtl);
                }
                index++;
            }
            return list;
        }

        protected internal IEnumerable<String[]> GetRecords()
        {
            String[] aRecord;
            String[] separator = { ";" };

            Stream stream = FileUtil.ReadFileStream(selectedFile);
            StreamReader reader = new StreamReader(stream);

            while (!reader.EndOfStream)
            {
                aRecord = reader.ReadLine().Split(separator, StringSplitOptions.RemoveEmptyEntries);

                yield return aRecord;
            }
        }

        private void CsvListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            
        }

    }

}